//
//  DetailViewController.m
//  iCarStyle
//
//  Created by liunian on 13-9-9.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "DetailViewController.h"
#import "TFHpple.h"
#import "Article.h"
#import "MREntitiesConverter.h"
#import "ArticleManager.h"
#import "WebViewController.h"
#import "MBButtonMenuViewController.h"
#import "AppDelegate.h"
#import "GADBannerView.h" 
#import "CoreDataManager.h"
#import "SGFocusImageFrame.h"
#import "SGFocusImageItem.h"

#define kDefaultBottomBarHeight           38

@interface DetailViewController ()<UIWebViewDelegate,MFMailComposeViewControllerDelegate,MBButtonMenuViewControllerDelegate,GADBannerViewDelegate,MKEnvObserverApplicationProtocol,SGFocusImageFrameDelegate>
@property (nonatomic, retain) UIImageView                *navImageView;
@property (nonatomic, retain) UIImageView                *bottomImageView;
@property (nonatomic, retain) UIActivityIndicatorView    *indicatorView;
@property (nonatomic, retain) UILabel                    *theTitle;
@property (nonatomic, retain) UIButton                   *favBtn;
@property (nonatomic, retain) UIButton                   *refreshBtn;
@property (nonatomic, retain) UIButton                   *forwardBtn;
@property (nonatomic, retain) UIButton                   *sourceBtn;
@property (nonatomic, strong) UILabel                    *textLabel;
@property (nonatomic, retain) Article                    *article;
@property (nonatomic, retain) GADBannerView              *banner;
@property (nonatomic, retain) MBButtonMenuViewController *menu;

@property (nonatomic, retain) UIScrollView  *scrollView;
@end

@implementation DetailViewController
- (void)dealloc{
    _banner.delegate = nil;
    RELEASE_SAFELY(_banner);
    MKRemoveApplicationObserver(self);
}
- (id)initWithArticle:(Article *)article
{
    self = [super init];
    if (self) {
        self.article = article;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    MKAddApplicationObserver(self);
    self.title = @"正文";
    [self.view addSubview:self.bottomImageView];
    self.navigationItem.leftBarButtonItem = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBarHidden = YES;
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:self.article.title, @"title", self.article.link, @"link",nil];
    [MobClick event:@"showNews" attributes:dict];
    [self.indicatorView startAnimating];
    dispatch_async(kBgQueue, ^{
        [self paser];
    });
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    [self updateUI];
//    [self updateADUI];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    self.navigationController.navigationBarHidden = NO;
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED < 70000

#else
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}
#endif

- (void)updateADUI{
    NetworkStatus status = MKGetCurrentNetworkStatus;
    if ([[ArticleManager sharedManager] isTodayClick] || status == kNotReachable) {
        _banner.delegate = self;
        REMOVE_SAFELY(_banner);
    }else{
        self.banner.delegate = self;
        [self.banner loadRequest:[GADRequest request]];
    }
}

#pragma mark MKEnvObserverApplicationProtocol
- (void)mkEnvObserverApplicationWillEnterForeground:(NSNotification *)notification{
    [self updateADUI];
}

- (void)initHeadViewWithImageBox:(NSArray *)images{
    NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:images.count];
    [images enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NewsImg *imageNews = obj;
        NSInteger tag = idx;
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:imageNews.alt
                                                                    image:imageNews.src
                                                                      tag:tag];
        [items addObject:item];
    }];

    SGFocusImageFrame *bannerView = [[SGFocusImageFrame alloc] initWithFrame:CGRectMake(0, 0, 320, 240) delegate:self imageItems:items isAuto:YES];
//    [bannerView scrollToIndex:2];
    [self.scrollView addSubview:bannerView];
}

- (void)paser{
    BMLog(@"\n%@",self.article.link);


    NewsArticle *articleNews = nil;

    NSMutableArray *textArray = nil;
    NSMutableArray *imgsArray = nil;

    articleNews = [[CoreDataManager sharedManager] newsArticleWithArticle:self.article];
    if (!articleNews.newsTexts) {
        NSData *htmlData;
        NSString *htmlStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:self.article.link] encoding:NSUTF8StringEncoding error:nil];
        htmlData = [htmlStr dataUsingEncoding:NSUTF8StringEncoding];

        OGDocument *document = [ObjectiveGumbo parseDocumentWithData:htmlData];
        OGElement *news_box = (OGElement *)[[document elementsWithClass:@"news_con_box"] firstObject];
        NSArray *ps = [news_box select:@"p"];
        for (OGElement *e in ps) {
            BMLog(@"--%@",[e text]);
        }

        if (ps) {
            textArray = [[NSMutableArray alloc] initWithCapacity:0];
            imgsArray = [[NSMutableArray alloc] initWithCapacity:0];
            [ps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                OGElement *element = obj;
                if ([element.text length]) {
                    NewsText *textNews = [[NewsText alloc] init];
                    textNews.nid = self.article.nid;
                    textNews.index = idx;
                    textNews.content = element.text;

                    [textArray addObject:textNews];
                    [[CoreDataManager sharedManager] insertNewsText:textNews];
                }else if ([element first:@"img"]){
                    OGElement *imgElement = (OGElement *)[element first:@"img"];
                    NSString *src = imgElement.attributes[@"_src"];
                    NSString *alt = imgElement.attributes[@"title"];
                    if (src && alt) {
                        NewsImg *imgNews = [[NewsImg alloc] init];
                        imgNews.nid = self.article.nid;
                        imgNews.index = idx;
                        imgNews.src = src;
                        imgNews.alt = alt;
                        [imgsArray addObject:imgNews];
                        [[CoreDataManager sharedManager] insertNewsImg:imgNews];
                    }

                }
                
            }];

            articleNews.newsTexts = textArray;
            articleNews.newsImages = imgsArray;
        }
    }

/*
        NSArray *p_left_texts = [news_box elementsWithAttribute:@"style" andValue:@"text-align:left"];
        NSArray *p_center_texts = [news_box elementsWithAttribute:@"style" andValue:@"text-align:center"];

        if (p_left_texts) {
            textArray = [[NSMutableArray alloc] initWithCapacity:p_left_texts.count];
        }

        [p_left_texts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            OGElement *element = obj;
            BMLog(@"\n%@",[element text]);
            NSString *text = [element text];
            if (text) {
                NewsText *textNews = [[NewsText alloc] init];
                textNews.nid = self.article.nid;
                textNews.index = idx;
                textNews.content = text;

                [textArray addObject:textNews];
                [[CoreDataManager sharedManager] insertNewsText:textNews];
            }
        }];

        if (p_center_texts) {
            imgsArray = [[NSMutableArray alloc] initWithCapacity:p_center_texts.count];
        }

        [p_center_texts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            OGElement *element = obj;
            OGElement *imgElement = (OGElement *)[element first:@"img"];
            NSString *src = imgElement.attributes[@"_src"];
            NSString *alt = imgElement.attributes[@"title"];
            if (src && alt) {
                NewsImg *imgNews = [[NewsImg alloc] init];
                imgNews.nid = self.article.nid;
                imgNews.index = idx;
                imgNews.src = src;
                imgNews.alt = alt;
                [imgsArray addObject:imgNews];
                [[CoreDataManager sharedManager] insertNewsImg:imgNews];
            }
        }];
        articleNews.newsTexts = textArray;
        articleNews.newsImages = imgsArray;
    }
*/
    dispatch_async(dispatch_get_main_queue(), ^{

        [self initHeadViewWithImageBox:articleNews.newsImages];
        [self.textLabel setText:[articleNews plainText]];

        CGSize size;
        NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                              self.textLabel.font, NSFontAttributeName,
                                              nil];
        CGRect frame = [self.textLabel.text boundingRectWithSize:CGSizeMake(300, NSIntegerMax)
                                                         options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin
                                                      attributes:attributesDictionary context:nil];;

        size = frame.size;

        CGRect rect = self.textLabel.frame;
        [self.textLabel setFrame:CGRectMake(CGRectGetMinX(rect), CGRectGetMinY(rect), CGRectGetWidth(rect), size.height)];
        [self.textLabel sizeThatFits:size];
        [self.textLabel setNeedsLayout];
        [self.scrollView setContentSize:CGSizeMake(320, CGRectGetMaxY(self.textLabel.frame) +20)];

    });
}

- (void)back{
    [self.navigationController popViewControllerWithNavigationControllerTransition];

}

- (void)updateUI{
    if ([[ArticleManager sharedManager] isFavArticle:self.article]) {
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_unfocus.png") forState:UIControlStateNormal];
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_focus.png") forState:UIControlStateHighlighted];
    }else{
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_focus.png") forState:UIControlStateNormal];
        [self.favBtn  setBackgroundImage:IMGNAMED(@"bt_unfocus.png") forState:UIControlStateHighlighted];
    }
}
- (void)sourceBtnClick{
    NSURL *url = [NSURL URLWithString:self.article.link];
    WebViewController *webVC = [[WebViewController alloc] initWithURL:url];
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)favBtnClick:(id)sender{
    if ([[ArticleManager sharedManager] isFavArticle:self.article]) {
        [[ArticleManager sharedManager] cancelFavArticle:self.article];
    }else{
        [[ArticleManager sharedManager] favArticle:self.article];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:self.article.title, @"title", self.article.link, @"link",nil];
        [MobClick event:@"collectNews" attributes:dict];
    }
    [self updateUI];
}
- (void)refreshBtnClick{

}

- (void)forwardBtnClick{
    [self.menu showInView:self.view];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        WebViewController *webVC = [[WebViewController alloc] initWithURL:request.URL];
        [self.navigationController pushViewController:webVC animated:YES];
        return NO;
    }
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    [self.indicatorView startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self.indicatorView stopAnimating];
    [self.theTitle setText:@"正文"];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [self.indicatorView stopAnimating];
}

#pragma mark - MBButtonMenuViewControllerDelegate
- (void)buttonMenuViewController:(MBButtonMenuViewController *)buttonMenu buttonTappedAtIndex:(NSUInteger)index
{
    [buttonMenu hide];
    switch (index) {
        case 0:
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.article.link]];
        }
            break;
        case 1:
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = self.article.link;
        }
            break;
        case 2:
        {
            MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
            
            mailViewController.mailComposeDelegate = self;
            [mailViewController setSubject:self.article.title];
            
            NSString *linkStr = [NSString stringWithFormat:@"来自：<a href=\"%@\" title=\"汽车助手\">汽车助手</a>",kLinkItunes];
            
//            if (self.webHtmlString) {
////                [mailViewController setMessageBody:self.webHtmlString isHTML:YES];
//            }else{
//                NSString *bodyStr = nil;
//                bodyStr = [self.article.desc stringByAppendingString:linkStr];
//                [mailViewController setMessageBody:self.article.desc isHTML:NO];
//            }

            mailViewController.modalPresentationStyle = UIModalPresentationFormSheet;
            [self presentViewController:mailViewController animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
    
}

- (void)buttonMenuViewControllerDidCancel:(MBButtonMenuViewController *)buttonMenu{
    [buttonMenu hide];
}
#pragma mark MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller
          didFinishWithResult:(MFMailComposeResult)result
                        error:(NSError *)error
{
	[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark GADBannerViewDelegate
- (void)adViewDidReceiveAd:(GADBannerView *)view{
}
#pragma mark GADBannerViewDelegate
- (void)adView:(GADBannerView *)view didFailToReceiveAdWithError:(GADRequestError *)error{
    BMLog(@"");
}
- (void)adViewWillPresentScreen:(GADBannerView *)adView{
    BMLog(@"");
}
- (void)adViewWillDismissScreen:(GADBannerView *)adView{
    BMLog(@"");
}
- (void)adViewDidDismissScreen:(GADBannerView *)adView{
    BMLog(@"");
    [[ArticleManager sharedManager] setTodayClick:YES];
    [self updateADUI];
}
- (void)adViewWillLeaveApplication:(GADBannerView *)adView{
    BMLog(@"");
    [[ArticleManager sharedManager] setTodayClick:YES];
    [self updateADUI];
}
#pragma mark getter
- (UIImageView *)navImageView{
    if (!_navImageView) {
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        _navImageView.userInteractionEnabled = YES;
        [_navImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        _navImageView.backgroundColor = [UIColor flatWhiteColor];
        [self.indicatorView setFrame:CGRectMake(CGRectGetWidth(_navImageView.frame) - 36 - 10, 5, 36, 36)];
        [_navImageView addSubview:self.indicatorView];
        
    }
    return _navImageView;
}

- (UIActivityIndicatorView *)indicatorView{
    if (!_indicatorView) {
        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _indicatorView.hidesWhenStopped = YES;
    }
    return _indicatorView;
}
- (UILabel *)theTitle{
    if (!_theTitle) {
        _theTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 260, 34)];
        _theTitle.backgroundColor = [UIColor clearColor];
        _theTitle.textAlignment = ALIGNTYPE_LEFT;
        _theTitle.font = FONT_TITLE(22.0f);
        _theTitle.textColor = [UIColor flatBlackColor];
        [self.navImageView addSubview:_theTitle];
    }
    return _theTitle;
}
- (UIButton *)favBtn{
    if (!_favBtn) {
        
        UIImage *imgTop = IMGNAMED(@"bt_unfocus.png");
        _favBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _favBtn.exclusiveTouch = YES;
        _favBtn.frame = CGRectMake(_bottomImageView.bounds.size.width- 3 *(imgTop.size.width+10), floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_favBtn addTarget:self action:@selector(favBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_favBtn setBackgroundImage:IMGNAMED(@"bt_focus.png") forState:UIControlStateNormal];
        [_favBtn setBackgroundImage:IMGNAMED(@"bt_unfocus.png") forState:UIControlStateHighlighted];
    }
    return _favBtn;
}

- (UIButton *)sourceBtn{
    if (!_sourceBtn) {
        UIImage *imgTop = IMGNAMED(@"btn_source.png");
        _sourceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _sourceBtn.exclusiveTouch = YES;
        _sourceBtn.frame = CGRectMake(_bottomImageView.bounds.size.width - 1*(imgTop.size.width+10), floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_sourceBtn addTarget:self action:@selector(sourceBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_sourceBtn setBackgroundImage:IMGNAMED(@"btn_source.png") forState:UIControlStateNormal];
        [_sourceBtn setBackgroundImage:IMGNAMED(@"btn_source_light.png") forState:UIControlStateHighlighted];
    }
    return _sourceBtn;
}
- (UIButton *)refreshBtn{
    if (!_refreshBtn) {
        
        UIImage *imgTop = IMGNAMED(@"btn_web_refresh.png");
        _refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _refreshBtn.exclusiveTouch = YES;
        _refreshBtn.frame = CGRectMake(_bottomImageView.bounds.size.width-4*(imgTop.size.width+10), floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_refreshBtn addTarget:self action:@selector(refreshBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_refreshBtn setBackgroundImage:IMGNAMED(@"btn_web_refresh.png") forState:UIControlStateNormal];
        [_refreshBtn setBackgroundImage:IMGNAMED(@"btn_web_refresh_light.png") forState:UIControlStateHighlighted];
    }
    return _refreshBtn;
}

- (UIButton *)forwardBtn{
    if (!_forwardBtn) {
        
        UIImage *imgTop = IMGNAMED(@"btn_forward.png");
        _forwardBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _forwardBtn.exclusiveTouch = YES;
        _forwardBtn.frame = CGRectMake(_bottomImageView.bounds.size.width-2 *(imgTop.size.width+10), floorf((_bottomImageView.bounds.size.height-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_forwardBtn addTarget:self action:@selector(forwardBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_forwardBtn setBackgroundImage:IMGNAMED(@"btn_forward.png") forState:UIControlStateNormal];
        [_forwardBtn setBackgroundImage:IMGNAMED(@"btn_forward_light.png") forState:UIControlStateHighlighted];
    }
    return _forwardBtn;
}
- (UIImageView *)bottomImageView{
    if (!_bottomImageView) {
        _bottomImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - kDefaultBottomBarHeight - _kSpaceHeight- 20 - 44, 320, kDefaultBottomBarHeight)];
        _bottomImageView.backgroundColor = [UIColor flatWhiteColor];
        _bottomImageView.userInteractionEnabled = YES;
        [_bottomImageView setImage:IMGNAMED(@"bottomTabBarBackground.png")];
        
        UIImage *imgBack = IMGNAMED(@"btn_back.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, floorf((_bottomImageView.bounds.size.height-imgBack.size.height)/2), imgBack.size.width, imgBack.size.height);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_bottomImageView addSubview:back];
        
        [_bottomImageView addSubview:self.sourceBtn];
        [_bottomImageView addSubview:self.favBtn];
        [_bottomImageView addSubview:self.refreshBtn];
        [_bottomImageView addSubview:self.forwardBtn];
        [back setBackgroundImage:IMGNAMED(@"btn_back.png") forState:UIControlStateNormal];
        [back setBackgroundImage:IMGNAMED(@"btn_back_light.png") forState:UIControlStateHighlighted];
    }
    return _bottomImageView;
}

- (UILabel *)textLabel{
    if (!_textLabel) {
        _textLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,
                                                                 _kSpaceHeight+240,
                                                                 300,
                                                                 self.scrollView.bounds.size.height - _kSpaceHeight - 240)];
        [_textLabel setFont:[UIFont systemFontOfSize:18]];
        [_textLabel setBackgroundColor:[UIColor clearColor]];
        [_textLabel setTextColor:[UIColor darkTextColor]];
        [_textLabel setNumberOfLines:0];
        [self.scrollView addSubview:_textLabel];
    }
    return _textLabel;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - kDefaultBottomBarHeight)];
        [_scrollView setBackgroundColor:[UIColor clearColor]];
//        [_scrollView setPagingEnabled:YES];
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (MBButtonMenuViewController *)menu{
    if (nil == _menu) {
        NSArray *titles = [NSArray arrayWithObjects:@"在Safari中打开",
                           @"拷贝该页网址",
                           @"邮件发送该网址",
                           @"取消", nil];
        _menu = [[MBButtonMenuViewController alloc] init];
        [_menu setButtonTitles:titles];
        [_menu setDelegate:self];
        [_menu setCancelButtonIndex:[[_menu buttonTitles] count]-1];
    }
    return _menu;
}
- (GADBannerView *)banner{
    if (!_banner) {
        _banner = [[GADBannerView alloc] initWithFrame:CGRectMake(0,0, GAD_SIZE_320x50.width, GAD_SIZE_320x50.height)];
        _banner.adUnitID = kAdUnitID;
        _banner.delegate = self;
        _banner.rootViewController = self;
        [self.view addSubview:_banner];
    }
    return _banner;
}
@end
